//*************************************************************************************************
// TRACE.CPP
//*************************************************************************************************
#include "stdafx.h"
#include <stdarg.h>
#include "Trace.h"

HANDLE fhTraceNew = INVALID_HANDLE_VALUE;

void Trace::CheckHandle(void)
{
	DWORD written;
	// If the file hasn't been opened yet, open it, seek to the end and write a header.
	if (fhTraceNew == INVALID_HANDLE_VALUE)
	{
		fhTraceNew = CreateFileA("TFSSSApiShim.log", GENERIC_WRITE, FILE_SHARE_READ, NULL,
							CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (fhTraceNew == INVALID_HANDLE_VALUE)
		{
			return;
		}
		SetFilePointer(fhTraceNew, 0L, 0L, FILE_END);
		WriteFile(fhTraceNew, "\r\nBeginning new trace\r\n", 23, &written, NULL);
	}
}
void Trace::CloseFile(void)
{
	CloseHandle(fhTraceNew);
}
//*************************************************************************************************
//*************************************************************************************************
void Trace::WriteStr(char *text)
{
	CheckHandle();
	DWORD written;

	//// If the file hasn't been opened yet, open it, seek to the end and write a header.
	//if (fhTrace == INVALID_HANDLE_VALUE)
	//{
	//	fhTrace = CreateFileA("TFSSSApiShim.log", GENERIC_WRITE, FILE_SHARE_READ, NULL,
	//						OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	//	if (fhTrace == INVALID_HANDLE_VALUE)
	//	{
	//		return;
	//	}
	//	SetFilePointer(fhTrace, 0L, 0L, FILE_END);
	//	WriteFile(fhTrace, "\r\nBeginning new trace\r\n", 23, &written, NULL);
	//}

	// Write the trace message and flush it in case of a crash.
	WriteFile(fhTraceNew, text, (int)strlen(text), &written, NULL);
	WriteFile(fhTraceNew, "\r\n", 2, &written, NULL);
	FlushFileBuffers(fhTraceNew);
}

//*************************************************************************************************
//*************************************************************************************************
void  Trace::Write(char *text, ...)
{
	va_list p;
	va_start(p, text);

    char rcExpanded[1024];
    vsprintf_s(rcExpanded, sizeof(rcExpanded)/sizeof(char), text, p);
    va_end(p);

	WriteStr(rcExpanded);
}

//*************************************************************************************************
//*************************************************************************************************
void  Trace::Write(LPWSTR text, ...)
{
	va_list p;
	va_start(p, text);

    WCHAR rcExpanded[1024];
    vswprintf_s(rcExpanded, sizeof(rcExpanded)/sizeof(WCHAR), text, p);
    va_end(p);

	char rcStr[1024];
	WideCharToMultiByte(CP_ACP, 0, rcExpanded , -1, rcStr, sizeof(rcStr), NULL, NULL);
	WriteStr(rcStr);
}

